package Verification;

import java.io.FileWriter;
import java.io.BufferedWriter;
import java.util.HashMap;
import java.lang.Exception;

public class Logger {

	// Log files
	public static final String AVERAGE_TIME = "atime.txt";
	public static final String AVERAGE_MEMORY = "amem.txt";
	public static final String AVERAGE_OCCURRENCES = "aocc.txt";
	public static final String DIMENSION = "dim.txt";

	private static final int NUMBER_OF_FILES = 4;

	/**
	 * Look-up table for log file indexes
	 */
	private HashMap<String, Integer> indexLut;

	/**
	 * File streams
	 */
	private FileWriter[] streams;

	/**
	 * Writers
	 */
	private BufferedWriter[] writers;

	/**
	 * Constructor of file logger.
	 *
	 * @throws Exception
	 *             exception on mismatch between expected number of logg files
	 *             and actual amount of logg files added to the look-up table.
	 */
	public Logger() {

		int index = 0;

		indexLut = new HashMap<String, Integer>();

		// Build look-up table here - lazy
		indexLut.put(AVERAGE_TIME, index++);
		indexLut.put(AVERAGE_OCCURRENCES, index++);
		indexLut.put(AVERAGE_MEMORY, index++);
		indexLut.put(DIMENSION, index++);

		// Create file stream array
		streams = new FileWriter[NUMBER_OF_FILES];

		// Create writer array
		writers = new BufferedWriter[NUMBER_OF_FILES];

		try {

			// Initialize files and writers for each logg
			for (String key : indexLut.keySet()) {

				// Get index
				index = indexLut.get(key);

				// Create stream
				streams[index] = new FileWriter(System.getProperty("user.dir") + "\\log\\" + key);

				// Create writer
				writers[index] = new BufferedWriter(streams[index]);
			}

		} catch (Exception e) {

			System.out.println(e.getMessage());
		}
	}

	/**
	 * Writes a line entry to specified logg file.
	 *
	 * @param identifier
	 *            String indentifier of logg file
	 * @param entry
	 *            Entry to put in logg file
	 */
	public void writeln(String identifier, String entry) {

		try {

			// Write to file
			writers[indexLut.get(identifier)].write(entry + System.getProperty("line.separator"));

		} catch (Exception e) {

			System.out.println(e.getMessage());
		}
	}

	public void close() {

		try {

			// Close all files
			for (BufferedWriter writer : writers) {

				writer.close();
			}

		} catch (Exception e) {

			System.out.println(e.getMessage());
		}
	}

	protected void finalize() {

		this.close();
	}
}
